package com.uci.photogam;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.uci.photogam.facebook.FacebookSSOActivity;

public class ActivityCamera extends Activity {
	private final String[] texts = { "Camera", "Gallery", "Share", "Facebook" };

	private static final int REQ_CODE_PICK_PICTURE = 0;
	private static final int REQ_CODE_TAKE_PICTURE = 2;

	private static final String IMG_SOURCE_CAMERA = "Camera";
	private static final String IMG_SOURCE_GALLERY = "Gallery";

	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	/** Create a file Uri for saving an image or video */

	private Uri imgUri;
	private String lastImgSelectedName;
	private String imageSource;
	private String galleryDir;

	private final static int CAMERA = 0;
	private final static int GALLERY = 1;
	private final static int SHARE = 2;
	private final static int FACEBOOK = 3;

	private GridView gridview;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		gridview = (GridView) findViewById(R.id.mainMenuGridview);
		gridview.setColumnWidth(metrics.widthPixels / 2);
		gridview.setAdapter(new AdapterMainMenu(this, texts, metrics));
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Intent i; // Intent for the switch cases
				switch (position) {
				case CAMERA:
					// create Intent to take a picture and return control to the
					// calling application
					i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					// Alexis: I'm getting an null pointer exception at this
					// line when I select camera
					imgUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
					// create a file to save the image
					i.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
					// set the image file name
					// start the image capture Intent
					startActivityForResult(i, REQ_CODE_TAKE_PICTURE);
					break;
				case GALLERY:
					// images on the SD card.
					i = new Intent(Intent.ACTION_PICK);
					i.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
					i.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, REQ_CODE_PICK_PICTURE);
					break;
				case SHARE:
					if (lastImgSelectedName == null) {
						V.toastMessage(ActivityCamera.this,
								"\tPlease specify an image \n with the camera or gallery first");
						break;
					}
					// This is the file to be sent via different services
					File downloadedPic = null;

					if (imageSource.equals(IMG_SOURCE_CAMERA)) {
						downloadedPic = new File(
								Environment
										.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
										+ "/MyCameraApp/", lastImgSelectedName);
						V.Log("FILE PATH", downloadedPic.getPath());
					} else if (imageSource.equals(IMG_SOURCE_GALLERY)) {
						downloadedPic = new File(galleryDir,
								lastImgSelectedName);
					}

					// Using the built in send intent
					i = new Intent(android.content.Intent.ACTION_SEND);
					i.setType("image/jpeg");
					// Sending this file via the different sending services
					// enabled on phone
					i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(downloadedPic));
					V.Log("Image location", downloadedPic.toURI().toString());

					// This is the self made sharing page
					// i = new Intent(ActivityCamera.this,
					// ActivityShare.class);
					startActivity(i);
					break;
				case FACEBOOK:
					i = new Intent(ActivityCamera.this,
							FacebookSSOActivity.class);
					startActivityForResult(i, V.REQ_CODE_PICK_PICTURE_FB);
					break;
				}
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("REQ CODE IS " , String.valueOf(requestCode));
		if (resultCode == RESULT_OK) {
			Intent i = new Intent(this, ActivityEditImage.class);
			switch (requestCode) {
			case REQ_CODE_TAKE_PICTURE:
				// Gets the file name
				lastImgSelectedName = imgUri.getLastPathSegment();
				System.out.println(lastImgSelectedName);
				V.Log("Taken with camera", imgUri.getLastPathSegment());
				V.Log("IMG DIRECTORY LOCATION", imgUri.getPath());
				i.putExtra(V.TAKEN_PICTURE, true);
				i.putExtra(V.IMAGE_PATH, imgUri.getPath());
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);
				imageSource = IMG_SOURCE_CAMERA;
				break;
			case REQ_CODE_PICK_PICTURE:
				imgUri = data.getData();
				// Whole pathName
				galleryDir = "/mnt/" + getRealImagePath(imgUri);
				// Gets the file name
				lastImgSelectedName = galleryDir.substring(
						galleryDir.lastIndexOf("/") + 1, galleryDir.length());

				i.putExtra(V.TAKEN_PICTURE, false);
				i.putExtra(V.IMAGE_PATH, galleryDir);
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);

				// Just the path, does not include filename
				galleryDir = galleryDir.substring(0,
						galleryDir.lastIndexOf("/") + 1);
				imageSource = IMG_SOURCE_GALLERY;

				break;
			case V.REQ_CODE_PICK_PICTURE_FB:
				Log.d("FB IMG LOCATION", "LAST ONE");

				Bundle bundle = data.getExtras();
				Bitmap image = (Bitmap) bundle.get("image");
				i.putExtra(V.TAKEN_PICTURE, false);
				i.putExtra(V.IMAGE_PATH, bundle.getString("imgUrl"));
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"MyCameraApp");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				V.Log("MyCameraApp", "failed to create directory");
				return null;
			}
		}
		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}
		return mediaFile;
	}

	public String getRealImagePath(Uri uriPath) {

		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uriPath, proj, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();
		String path = cursor.getString(index);
		path = path.substring(5);

		return path;
	}

}